package ru.space_game.gui;

import static org.lwjgl.opengl.GL11.*;
import ru.space_game.core.Game;
import ru.space_game.entities.Entity;
import ru.space_game.entities.ShipEntity;
import ru.space_game.resource.Sprite;

public class MiniMap {

	private int x;

	private int y;

	private Sprite sprite;

	protected MiniMap(int x, int y, Sprite sprite) {
		this.x = x;
		this.y = y;
		this.sprite = sprite;
	}

	public void draw() {
		sprite.draw(x, y, 0);
		ShipEntity ship = Game.getInstance().getWorld().getShip();
		// TODO move draw logic to Entity classes
		for (Entity entity : Game.getInstance().getWorld().getEntities()) {
			if (!(entity instanceof ShipEntity)
					&& entity.rangeTo(ship) < ship.getDetectRadius()) {
				double deltaX = (double) (entity.getX() - ship.getX());
				double deltaY = (double) (entity.getY() - ship.getY());
				double alpha = Math.atan(deltaY / deltaX);
				if (ship.getX() > entity.getX())
					alpha += Math.PI;
				double range = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
				double scale = (double) sprite.getWidth()
						/ (double) ship.getDetectRadius() / 2;

				// store the current model matrix
				glPushMatrix();

				// translate to the right location and prepare to draw
				glTranslatef(x + (float) (range * Math.cos(alpha) * scale), y
						+ (float) (range * Math.sin(alpha) * scale), 0);

				glColor3f((entity.getMiniMapColor() >> 24) & 0xff,
						(entity.getMiniMapColor() >> 16) & 0xff,
						(entity.getMiniMapColor() >> 8) & 0xff);
				// draw a quad textured to match the sprite
				glBegin(GL_QUADS);
				{
					glTexCoord2f(0, 0);
					glVertex2f(-2, -2);

					glTexCoord2f(1, 0);
					glVertex2f(2, -2);

					glTexCoord2f(1, 1);
					glVertex2f(2, 2);

					glTexCoord2f(0, 1);
					glVertex2f(-2, 2);
				}
				glEnd();

				glColor3f(1.0f, 1.0f, 1.0f);

				// restore the model view matrix to prevent contamination
				glPopMatrix();
			}
		}
	}

}
